package config

import (
	"fmt"
	"net"
	"os"
	"strings"
)

// GetPort 获取端口，如果未设置则返回默认值8080
func GetPort() string {
	port := os.Getenv("START_PORT")
	if port == "" {
		port = "8080"
	}
	// 获取IPv4 localhost 和 IPv6 localhost
	local := net.JoinHostPort("localhost", port)
	localHost := net.JoinHostPort("127.0.0.1", port)
	// 获取机器实际IP地址
	ips, _ := GetLocalIPs()
	// 打印信息
	fmt.Println(strings.Repeat("-", 60))
	fmt.Println("\tApplication Jeecg-Boot is running! Access URLs:")
	fmt.Printf("\tLocal:\t\thttp://%s/\n", local)
	fmt.Printf("\tLocalHost:\thttp://%s/\n", localHost)
	for _, ip := range ips {
		extHost := net.JoinHostPort(ip, port)
		fmt.Printf("\tExternal:\thttp://%s/\n", extHost)
		fmt.Printf("\tSwagger文档:\thttp://%s/swagger/index.html\n", extHost)
	}
	fmt.Println(strings.Repeat("-", 60))
	return port
}

// GetLocalIPs 获取本地IP地址列表
func GetLocalIPs() ([]string, error) {
	var ips []string
	addr, err := net.InterfaceAddrs()
	if err != nil {
		return ips, err
	}
	for _, address := range addr {
		// Check if it's an IP address and not loopback
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ips = append(ips, ipNet.IP.String())
			}
		}
	}
	return ips, nil
}
